package com.hsu.hiring.talent.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hsu.hiring.talent.dao.ResumeDao;
import com.hsu.hiring.talent.entity.ResumeEntity;

/**
 * <pre>
 * 控制层（MVC的C层）：
 * 1、接收前台传来的参数
 * 2、调用业务逻辑
 * 3、控制转向
 * </pre>
 *
 * @author Hsu.
 * @since 2016年1月11日
 */
public class ResumeServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private ResumeDao resumeDao = new ResumeDao();

	/**
	 * 表单的method="get"或地址栏提交会调用到此方法
	 */
	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	/**
	 * 表单的method="post"提交会调用到此方法
	 */
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// 避免中文乱码
		request.setCharacterEncoding("UTF-8");
		String command = request.getParameter("command");
		if ("add".equals(command)) {
			add(request, response);
		} else if ("list".equals(command)) {
			list(request, response);
		} else {
			throw new IllegalStateException("请求非法~");
		}
	}

	/**
	 * 简历的新增
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void add(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1、获取前台传过来的参数
		int talentId = Integer.parseInt(request.getParameter("talent_id"));
		String intention = request.getParameter("intention");
		String workExperience = request.getParameter("work_experience");
		String projectExperience = request.getParameter("project_experience");

		// 2、调用业务逻辑
		ResumeEntity resumeEntity = new ResumeEntity();
		resumeEntity.setTalentId(talentId);
		resumeEntity.setIntention(intention);
		resumeEntity.setWorkExperience(workExperience);
		resumeEntity.setProjectExperience(projectExperience);
		int row = resumeDao.add(resumeEntity);

		// 3、转向
		request.getRequestDispatcher(
				"view/talent/resume-success.jsp?row=" + row).forward(request,
				response);
	}

	/**
	 * 简历查询
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void list(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1、获取前台传过来的参数
		// 2、调用业务逻辑
		List<ResumeEntity> resumeList = resumeDao.list();
		// 3、转向
		request.setAttribute("resumeList", resumeList);
		request.getRequestDispatcher("view/talent/resume-success.jsp").forward(
				request, response);
	}
}
